﻿CREATE PROCEDURE dbo.s_Tracker_Car_Remove__Cancel
	@TrackerRequestID int
AS

BEGIN TRAN

INSERT INTO t_Tracker_Car(TrackerID,VIN,TechnicianID,DateStamp)
SELECT tt.TrackerID,tr.VIN,tt.TechnicianID,htc.DateStamp
FROM t_Technician_Tracker tt
INNER JOIN t_TrackerRequest tr ON tt.TrackerRequestID = tr.ID
CROSS JOIN (SELECT MAX(HID) AS HID FROM vhist_t_Tracker_Car WHERE TrackerRequestID = @TrackerRequestID) AS HID
INNER JOIN vhist_t_Tracker_Car AS htc ON htc.HID = HID.HID
WHERE tr.ID = @TrackerRequestID

IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

DELETE FROM t_Technician_Tracker WHERE TrackerRequestID = @TrackerRequestID

IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

/**/DECLARE @CI int EXEC @CI = sp__Context_WorkFlow_System 1
UPDATE t_Tracker SET StatusID = dbo.TrackerStatusBack(ID)
WHERE ID IN (SELECT TrackerID FROM t_Tracker_Car WHERE TrackerRequestID = @TrackerRequestID)
/**/IF @@ERROR = 0 COMMIT TRAN ELSE ROLLBACK TRAN
/**/EXEC sp__Context @CI


